package com.lujieni.nio.c2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false); //配置获取连接是非阻塞的
        server.bind(new InetSocketAddress(8080)); //监听8080端口

        List<SocketChannel> list = new ArrayList<>();

        ByteBuffer allocate = ByteBuffer.allocate(1);

        while (true){
            SocketChannel accept = server.accept(); //获取客户端的连接,SocketChannel用来和客户端通信
            if(accept != null){ //如果连接不为空说明有客户端已经进来了
                list.add(accept);
                accept.configureBlocking(false); // 非阻塞模式
            }
            for (SocketChannel channel: list) {
                int read = channel.read(allocate);
                if(read > 0){ // 大于0代表客户端有输入流来
                    allocate.flip(); // 读模式
                    System.out.println(StandardCharsets.UTF_8.decode(allocate));
                    allocate.clear(); // 写模式
                }
            }
        }
    }
}
